package org.bunny.vehicle.servlet;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bunny.vehicle.entity.User;
import org.bunny.vehicle.util.Const;
import org.bunny.vehicle.util.Utils;

import com.alibaba.fastjson.JSONObject;

public class AuthenticationFilter implements Filter {

	private static final Log log = LogFactory.getLog(AuthenticationFilter.class);

	@Override
	public void init(FilterConfig config) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;

		final String requestUri = StringUtils.substringAfter(httpRequest.getRequestURI(),
				httpRequest.getContextPath() + "/");
		if (Utils.startsWithIgnoreCase(requestUri, Const.ALLOW_NOT_LOGIN)) {
			chain.doFilter(request, response);
			return;
		}

		HttpServletResponse httpResponse = (HttpServletResponse) response;
		HttpSession session = httpRequest.getSession(false);

		// 从 Session 中取登录用户信息，如果无法取得，则尝试从 Cookie 中获取
		if (null == session || null == session.getAttribute(Const.SESSION_USER)) {
			if (null != httpRequest.getCookies()) {
				for (Cookie cookie : httpRequest.getCookies()) {
					if (Const.COOKIE_USER.equalsIgnoreCase(cookie.getName())) {
						try {
							String json = URLDecoder.decode(cookie.getValue(), Const.CHARSET);
							log.info("Cookie Login: " + json);
							User user = JSONObject.parseObject(json, User.class);
							session = httpRequest.getSession();
							session.setAttribute(Const.SESSION_USER, user);
						} catch (Exception e) {
							log.error(e, e);
						}
						break;
					}
				}
			}
		}

		if (null == session || null == session.getAttribute(Const.SESSION_USER)) {
			forwardLogin(httpRequest, httpResponse); // 无法取得登录用户信息，返回登录页面
			return;
		} else {
			User user = (User) session.getAttribute(Const.SESSION_USER);
			if (User.CLASS_ADMIN > user.getClassification()
					&& Utils.startsWithIgnoreCase(requestUri, Const.ADMIN_PREFIX)) { // 管理员权限判断
				session.removeAttribute(Const.SESSION_USER);
				forwardLogin(httpRequest, httpResponse);
				return;
			} else if (User.CLASS_DRIVER > user.getClassification()
					&& Utils.startsWithIgnoreCase(requestUri, Const.DRIVER_PREFIX)) { // 司机权限判断
				session.removeAttribute(Const.SESSION_USER);
				forwardLogin(httpRequest, httpResponse);
				return;
			}
		}

		chain.doFilter(httpRequest, httpResponse);
	}

	@Override
	public void destroy() {

	}

	private void forwardLogin(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.sendRedirect(request.getContextPath() + "/login.html");
	}

}
